<template>
  <div class="">
    <div class="flex-column">
      <!-- <div class="flex-row" style="justify-content: space-between">
          <div class="content-txt1">通航环境</div>
          <div @click="handToParentClose()">
            <i class="el-icon-circle-close" style="color: #409eff"></i>
          </div>
        </div> -->
      <!-- <div class="line"></div> -->
      <div class="condition">
        <div class="condition_item">
          <div class="condition_item_inp">
            <input type="text" v-model="searchText" @input="handleSearch" placeholder="输入名称查找" class="inp" />
          </div>
        </div>
      </div>

      <div class="shipContent" v-infinite-scroll="load" :infinite-scroll-disabled="infiniteScrollDisabled">
        <el-collapse accordion v-model="activeNames">
          <el-collapse-item v-for="item in datalist" :key="item.id" :name="item.id">
            <template #title>
              <div style="display: flex; align-items: center; width: 100%">
                <div style="
                      width: 100%;
                      height: 100%;
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                    " @click="changeCollapse(item)">
                  <div style="display: flex; align-items: center">
                    <el-icon class="iconcolor" :class="{ active: item.isActive }" style="margin: 0 5px"><ArrowRight /></el-icon>
                    <div class="envName">{{ item.name }}</div>
                  </div>

                  <div class="el-collapse-right">
                    <!-- <span class="iconfont icon-eye"></span> -->
                    <span class="iconfont icon-iconfonticon02 el-icon" @click.stop="handToAdd(item)"></span>
                  </div>
                </div>
              </div>
            </template>
            <div v-for="ite in item.list" :key="ite.id" class="envItem">
              <div>{{ ite.name }}</div>
              <div style="display: flex; align-items: center">
                <div class="envFun">
                  <el-tooltip class="item" effect="dark" content="规则" placement="bottom">
                    <el-icon @click.stop="setrule(ite)"><Setting /></el-icon>
                  </el-tooltip>
                </div>
                <div class="envFun">
                  <el-tooltip class="item" effect="dark" content="修改" placement="bottom">
                    <el-icon @click.stop="handToEdit(ite)"><Edit /></el-icon>
                  </el-tooltip>
                </div>
                <div class="envFun">
                  <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
                    <el-icon @click.stop="handToDelete(item, ite)"><Delete /></el-icon>
                  </el-tooltip>
                </div>
              </div>
            </div>
            <div class="envloading" @click="nextPage(item)" v-if="item.list.length < item.envtotal">
              点击加载更多
            </div>
          </el-collapse-item>
        </el-collapse>

        <!-- <el-tree
                ref="tree"
                :data="datalist"
                :props="defaultProps"
                expand-on-click-node
                node-key="id"
                :filter-node-method="filterNode"
                empty-text="暂无数据"
                @node-expand="changeEnv"
                @node-collapse="closeNode"
              >
                <div slot-scope="{ node, data }" class="custom-tree-node">
                  <div @click.stop="handleNodeClick(data)">
                    <span class="custom-tree-node-label">{{ node.label }}</span>
                  </div>
                  <div v-if="node.level == 1">
                    <i
                      @click.stop="handToAdd(data)"
                      class="el-icon-plus"
                      style="color: #409eff"
                    ></i>
                  </div>
                  <div v-if="node.level == 2">
                    <i
                      @click.stop="handToEdit(data)"
                      class="el-icon-edit-outline"
                      style="color: #409eff"
                    ></i>
                    <i
                      @click.stop="handToDelete(data)"
                      class="el-icon-delete"
                      style="color: #409eff; margin-left: 5px"
                    ></i>
                  </div>
                </div>
              </el-tree> -->
      </div>
    </div>
    <!-- </el-tab-pane>
      </el-tabs> -->
    <!-- 观测截面弹窗 -->
    <div class="add-view" v-if="isAddShow">
      <div class="flex-row" style="justify-content: space-between">
        <div class="content-txt1">{{ title }}</div>
        <div @click="clickToClose">
          <el-icon style="color: #409eff; font-size: 22px;"><CircleClose /></el-icon>
        </div>
      </div>
      <!-- <el-input v-model="form.name" type="text" placeholder="名称" /> -->
      <div class="addBox_list_inp">
        <el-input v-model="form.name" type="text" placeholder="名称"></el-input>
      </div>
      <el-input v-model="form.regions" type="textarea" :row="5" resize="none" placeholder="分界线"
        :readonly="true"></el-input>
      <div class="flex-row">
        <div class="content-txt1" @click="clickToParentEditLine()" style="margin-right: 10px">
          编辑<el-icon style="color: #409eff"><EditPen /></el-icon>
        </div>
        <div class="content-txt1" @click="clickAddLine()" style="margin-right: 10px"
          v-if="onData.envKey == 'shipping_lane' || onData.envType == 'shipping_lane'">
          编辑2<el-icon style="color: #409eff"><EditPen /></el-icon>
        </div>
        <div class="content-txt1" @click="clickToClearLine()">
          清除<el-icon style="color: #409eff"><Delete /></el-icon>
        </div>
      </div>
      <!-- <el-input v-model="form.beizhu" type="text" placeholder="备注" /> -->
      <div class="addBox_list_inp">
        <el-input v-model="form.remark" type="text" placeholder="备注"></el-input>
      </div>
      <div class="flex-row" style="justify-content: flex-end">
        <el-button type="primary" size="small" @click="clickToSave">保存</el-button>
        <el-button size="small" @click="clickToClose">取消</el-button>
      </div>
    </div>
    <!-- 编辑工具 -->
    <!-- <div class="edit-tool" v-if="isToolShow">
        <div class="content-txt1">线框</div>
        <el-color-picker
          v-model="form.color1"
          color-format="rgb"
          @change="changeColor1"
        ></el-color-picker>
        <el-input-number
          v-model="form.num"
          :min="1"
          :max="10"
          size="mini"
          @change="changeNUm"
        ></el-input-number>
        <el-switch
          v-model="form.linetype"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="实线"
          inactive-text="虚线"
          @change="changeLinetype"
        >
        </el-switch>
        <div class="column-line"></div>
        <div class="content-txt1" v-if="form.parentid != 1">填充</div>
        <el-color-picker
          v-if="form.parentid != 1"
          v-model="form.color2"
          color-format="rgb"
          @change="changeColor2"
        ></el-color-picker>
        <div class="column-line" v-if="form.parentid != 1"></div>
        <el-button
          @click="clickToToolClear()"
          type="danger"
          icon="el-icon-close"
          size="mini"
          circle
        ></el-button>
        <el-button
          @click="clickToToolSubmit()"
          type="success"
          icon="el-icon-check"
          size="mini"
          circle
        ></el-button>
      </div> -->
    <div v-if="isToolShow" class="toolsBox">
      <drawTools @Tools="setTools" @closeTools="clickToToolClear" @subTools="clickToToolSubmit" :isBtn="true" />
      <div class="btns"></div>
    </div>

    <el-dialog title="新增" v-model="isAddType" width="30%" :modal="false">
      <div class="typeBox">
        <div>
          <div class="typeBox_title">名称：</div>
          <el-input class="elinp" placeholder="请输入内容" v-model="typeForm.name"></el-input>
        </div>
        <div>
          <div class="typeBox_title">key：</div>
          <el-input class="elinp" placeholder="请输入内容（唯一）" v-model="typeForm.envKey"></el-input>
        </div>
        <div>
          <div class="typeBox_title">备注：</div>
          <el-input class="elinp" placeholder="请输入内容" v-model="typeForm.remark"></el-input>
        </div>
        <div>
          <div class="typeBox_title">排序：</div>
          <el-input class="elinp" type="Number" placeholder="请输入内容" v-model="typeForm.sort"></el-input>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeType">取 消</el-button>
          <el-button type="primary" @click="submitType">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog :title="ruleTitle" v-model="isrule" width="30%" :modal="false">
      <ruleVue :ruleData="ruleData" />
    </el-dialog>
    <div class="infoWindow" v-if="envirShow" :style="{ left: tranLeft, top: tranTop }">
      <div class="infoWindow_title">{{ envirData.title }}</div>
      <div class="infoWindow_text">
        <div>名称:</div>
        <div>{{ envirData.title }}</div>
      </div>
      <div class="infoWindow_text">
        <div>类型:</div>
        <div>{{ envirData.type }}</div>
      </div>
      <div class="infoWindow_text">
        <div>备注:</div>
        <div>{{ envirData.remark }}</div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, watch, getCurrentInstance, computed } from 'vue';
import { 
  ArrowRight, 
  Setting, 
  Edit, 
  Delete, 
  CircleClose, 
  EditPen,
} from '@element-plus/icons-vue';
import { ElInfiniteScroll } from 'element-plus';
import drawTools from "@/views/WindPower/drawingTools.vue";
import ruleVue from "@/views/WindPower/rule.vue";
import { Place } from "@/utils/request.js";
import {
  envType,
  envTypeList,
  env,
  envList,
  delEnv,
  editEnv,
} from "@/api/map/map.js";
import { ElMessage, ElMessageBox } from 'element-plus';
import plotIcon from '@/assets/plotting/pl1.png';

// 声明天地图API的全局变量
declare global {
  interface Window {
    T: any;
  }
}

// 类型定义
interface Point {
  lng: number;
  lat: number;
}

interface Item {
  id: number;
  name: string;
  list: EnvItem[];
  envtotal: number;
  isShow: boolean;
  isActive: boolean;
  envKey?: string;
  level?: number;
}

interface EnvItem {
  id: number;
  name: string;
  regions: string;
  points?: Point[];
  envType?: string | number;
  remark?: string;
  borderColor?: string;
  borderWidth?: number;
  fillColor?: string;
  display?: boolean;
  regions2?: string;
  [key: string]: any;
}

interface FormType {
  name: string | null;
  remark: string | null;
  borderType: number | null;
  borderColor: string | null;
  fillColor: string | null;
  regions: string | null;
  borderWidth: number | null;
  envType: string | null;
  envTypeId: number | null;
  points: Point[][];
  id?: number;
  line?: any;
  isFence?: boolean;
  place?: string;
  display?: boolean;
  regions2?: string;
}

interface TypeForm {
  name: string | null;
  envKey: string | null;
  remark: string | null;
  sort: number | null;
}

interface ToolsType {
  imgUrl: string;
  borderColor: string;
  borderWidth: number;
  isSolid: boolean;
  paddColor: string | null;
}

interface EnvParams {
  envType: string | null;
  pageNum: number;
  pageSize: number;
  envTypeId: number | null;
  place?: string;
}

interface EnvirData {
  title: string;
  type: string;
  remark: string;
}

interface MapEvent {
  currentLnglats: Point[];
  containerPoint?: {
    x: number;
    y: number;
  };
  [key: string]: any;
}

// 定义props
const props = defineProps({
  isShow: {
    type: Boolean,
    default: false
  },
  map: {
    type: Object,
    required: true
  }
});

// 定义emits
const emit = defineEmits(['handToClose', 'leftContent', 'envType', 'mouseover', 'mouseout']);

// 数据和状态
const place = ref<string>('');
const isAddShow = ref<boolean>(false);
const isAddType = ref<boolean>(false);
const isToolShow = ref<boolean>(false);
const title = ref<string>('');
const total = ref<number>(0);
const typeForm = reactive<TypeForm>({
  name: null,
  envKey: null,
  remark: null,
  sort: null
});
const form = reactive<FormType>({
  name: null,
  remark: null,
  borderType: null,
  borderColor: null,
  fillColor: null,
  regions: null,
  borderWidth: null,
  envType: null,
  envTypeId: null,
  points: []
});
const handler = ref<any>(null);
const line = ref<any>(null);
const datalist = ref<Item[]>([]);
const makers = ref<any[]>([]);
const lines = ref<any[]>([]);
const onData = reactive<any>({});
const tools = reactive<ToolsType>({
  imgUrl: plotIcon,
  borderColor: "#409EFF",
  borderWidth: 3,
  isSolid: true,
  paddColor: null
});
const isTools = ref<boolean>(true);
const filterText = ref<string>('');
const activeNames = ref<number[]>([]);
const envs = ref<EnvItem[]>([]);
const polygon = ref<any>(null);
const isrule = ref<boolean>(false);
const ruleData = ref<EnvItem | null>(null);
const ruleTitle = ref<string | null>(null);
const earlyMakers = ref<any[]>([]);
const envirData = reactive<EnvirData>({
  title: '',
  type: '',
  remark: ''
});
const envirShow = ref<boolean>(false);
const tranLeft = ref<string>('0');
const tranTop = ref<string>('0');
const envParams = reactive<EnvParams>({
  envType: null,
  pageNum: 1,
  pageSize: 500,
  envTypeId: null
});
const searchText = ref<string>('');
const infiniteScrollDisabled = ref<boolean>(false);

// 监听isTools变化
watch(isTools, () => {
  setPolygonTool();
});

// 地图API辅助函数
const mapUtils = {
  createPolygon(points: Point[], options: any) {
    const T = window.T;
    return new T.Polygon(points, options);
  },
  createPolyline(points: Point[], options: any) {
    const T = window.T;
    return new T.Polyline(points, options);
  },
  createLngLat(lng: number, lat: number) {
    const T = window.T;
    return new T.LngLat(lng, lat);
  },
  createPolygonTool(map: any, options: any) {
    const T = window.T;
    return new T.PolygonTool(map, options);
  },
  createPolylineTool(map: any, options: any) {
    const T = window.T;
    return new T.PolylineTool(map, options);
  }
};

// 生命周期钩子
onMounted(() => {
  place.value = String(Place);
  getenvTypeList();
  getwholeEnv();
  getenvList(Place);
});

onBeforeUnmount(() => {
  if (earlyMakers.value.length > 0) {
    earlyMakers.value.forEach((ele) => {
      props.map.removeOverLay(ele);
    });
  }
  emit('leftContent');
});

// 方法
const handleNodeClick = (data: Item) => {
  if (data.level !== 1 && data.points?.[0]) {
    props.map.panTo(
      mapUtils.createLngLat(data.points[0].lng, data.points[0].lat),
      12
    );
    setLine(data.points);
  }
};

const handToParentClose = () => {
  isToolShow.value = false;
  isAddShow.value = false;
  makers.value.forEach((ele) => {
    props.map.removeOverLay(ele);
  });
  emit('handToClose', 'environment');
};

// 分界线编辑
const clickToEditLine = () => {
  if (handler.value) {
    handler.value.close();
  }
  
  handler.value = mapUtils.createPolygonTool(props.map, {
    color: tools.borderColor,
    weight: tools.borderWidth,
    opacity: 0.5,
    fillColor: tools.paddColor,
    fillOpacity: 0.5,
    lineStyle: tools.isSolid ? "solid" : "dashed",
  });
  
  handler.value.open();
  handler.value.addEventListener("draw", (e: MapEvent) => {
    isAddShow.value = true;
    handler.value.clear();
    drawFinishLine(e);
  });
};

const drawFinishLine = (e: MapEvent) => {
  const list = e.currentLnglats;
  form.points.push(list);
  form.regions = JSON.stringify(form.points);
  
  polygon.value = mapUtils.createPolygon(list, {
    color: tools.borderColor,
    weight: tools.borderWidth,
    opacity: 0.5,
    fillColor: tools.paddColor,
    fillOpacity: 0.5,
    lineStyle: tools.isSolid ? "solid" : "dashed",
  });

  // 落线
  props.map.addOverLay(polygon.value);
  makers.value.push(polygon.value);
};

const drawLine = (e: MapEvent) => {
  const list = e.currentLnglats;
  form.points.push(list);
  form.regions2 = JSON.stringify(form.points);
  
  polygon.value = mapUtils.createPolyline(list, {
    color: tools.borderColor,
    weight: tools.borderWidth,
    opacity: 0.5,
    lineStyle: tools.isSolid ? "solid" : "dashed",
  });

  // 落线
  props.map.addOverLay(polygon.value);
  makers.value.push(polygon.value);
};

// 分界线编辑
const clickToParentEditLine = () => {
  isToolShow.value = true;
  isAddShow.value = false;
  if (!form.line) {
    clickToEditLine();
  }
};

const clickAddLine = () => {
  isAddShow.value = false;
  if (handler.value) {
    handler.value.close();
  }
  
  handler.value = mapUtils.createPolylineTool(props.map, {
    color: tools.borderColor,
    weight: tools.borderWidth,
    opacity: 0.5,
    lineStyle: tools.isSolid ? "solid" : "dashed",
  });
  
  handler.value.open();
  handler.value.addEventListener("draw", (e: MapEvent) => {
    isAddShow.value = true;
    handler.value.clear();
    drawLine(e);
  });
};

// 分界线清除
const clickToClearLine = () => {
  form.line = '';
};

// 分界线取消编辑
const clickToToolClear = () => {
  if (makers.value.length > 0) {
    makers.value.forEach((ele) => {
      props.map.removeOverLay(ele);
    });
  }
  handler.value.close();
  isToolShow.value = false;
  isAddShow.value = true;
};

// 分界线提交编辑
const clickToToolSubmit = () => {
  form.borderColor = tools.borderColor;
  form.borderType = tools.isSolid ? 1 : 2;
  form.fillColor = tools.paddColor;
  form.borderWidth = tools.borderWidth;

  isToolShow.value = false;
  isAddShow.value = true;
};

// 删除
const handToDelete = (item: Item, ite: EnvItem) => {
  ElMessageBox.confirm('是否确认删除"' + ite.name + '"？')
    .then(() => {
      return delEnv(ite.id);
    })
    .then(() => {
      ElMessage.success("删除成功");
      envParams.pageNum = 1;
      envParams.envTypeId = item.id;
      getenvList(item);
      getwholeEnv();
      emit("leftContent");
    })
    .catch(() => {
      // 取消删除时的处理
    });
};

// 编辑
const handToEdit = (data: EnvItem) => {
  Object.assign(onData, data);
  title.value = "编辑观测截面";
  Object.assign(form, data);
  form.points = [];
  isAddShow.value = true;
  if (data.regions) {
    form.points = JSON.parse(data.regions);
  }
};

// 新增取消
const clickToClose = () => {
  if (line.value) {
    props.map.removeOverLay(line.value);
  }

  isToolShow.value = false;
  isAddShow.value = false;
};

// 新增
const handToAdd = (data: Item) => {
  Object.assign(onData, data);
  if (line.value) {
    props.map.removeOverLay(line.value);
  }
  Object.assign(form, {
    name: null,
    remark: null,
    borderType: null,
    borderColor: null,
    fillColor: null,
    regions: null,
    borderWidth: null,
    envType: null,
    points: [],
  });
  form.envTypeId = data.id;
  form.envType = data.envKey;
  title.value = "新增观测截面";
  isAddShow.value = true;
  isToolShow.value = false;
};

// 保存
const clickToSave = () => {
  if (!form.name) {
    ElMessage({
      message: "名称不能为空",
      type: "warning",
    });
    return;
  }
  if (!form.id && form.id != 0) {
    form.isFence = true;
    form.place = place.value;
    if (onData.envKey == "shipping_lane") {
      form.display = false;
    }
    env(form).then((res: any) => {
      if (res.code == 200) {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        isAddShow.value = false;

        getwholeEnv();
        getenvList(onData);
        props.map.removeOverLay(polygon.value);
        emit("leftContent");
      }
    });
  } else {
    editEnv(form).then((res: any) => {
      if (res.code == 200) {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        isAddShow.value = false;
        getwholeEnv();
        getenvList(onData);
        props.map.removeOverLay(polygon.value);
        emit("leftContent");
      }
    });
  }
};

// 绘制管道线
const setLine = (points: Point[]) => {
  const line = mapUtils.createPolyline(points, {
    color: "#f47a55",
    weight: 5,
  });
  makers.value.push(line);
  props.map.addOverLay(line);
};

// 接收设置的绘制工具选项值
const setTools = (val: ToolsType) => {
  Object.assign(tools, val);
  isTools.value = !isTools.value;
};

// 设置多边形
const setPolygonTool = () => {
  if (!handler.value) return;
  
  handler.value.close();
  
  handler.value = mapUtils.createPolygonTool(props.map, {
    color: tools.borderColor,
    weight: tools.borderWidth,
    opacity: 0.5,
    fillColor: tools.paddColor,
    fillOpacity: 0.5,
    lineStyle: tools.isSolid ? "solid" : "dashed",
  });
  
  handler.value.open();
  handler.value.addEventListener("draw", (e: MapEvent) => {
    handler.value.clear();
    drawFinishLine(e);
  });
};

// 获取通航环境类型列表
const getenvTypeList = () => {
  envTypeList({
    isFence: 1,
  }).then((res: any) => {
    if (res.code == 200) {
      const rows = res.rows.map((ele: any) => {
        return {
          ...ele,
          list: [],
          envtotal: 0,
          isShow: false,
          isActive: false
        };
      });
      datalist.value.push(...rows);
      total.value = res.total;
      emit("envType", datalist.value);
    }
  });
};

// 根据类型获取通航环境列表
const getenvList = (obj: any) => {
  envList(envParams).then((res: any) => {
    if (res.code == 200) {
      if (envParams.pageNum == 1) {
        obj.list = res.rows;
      } else {
        obj.list.push(...res.rows);
      }
      obj.envtotal = res.total;
    }
  }).catch((err: any) => {
    console.log(err);
  });
};

// 获取全部通航环境列表
const getwholeEnv = () => {
  envList({
    place: place.value,
  }).then((res: any) => {
    if (res.code == 200) {
      envs.value = res.rows;
      setEarlyWarning(envs.value);
    }
  });
};

// 新增通航环境类型
const addEnvType = () => {
  isAddType.value = true;
};

// 关闭新增环境类型弹窗
const closeType = () => {
  Object.assign(typeForm, {
    name: null,
    envKey: null,
    remark: null,
    sort: null,
  });
  isAddType.value = false;
};

// 新增环境类型提交
const submitType = () => {
  if (!typeForm.name) {
    return ElMessage({
      message: "请输入名称",
      type: "warning",
    });
  }
  if (!typeForm.envKey) {
    return ElMessage({
      message: "请输入KEY",
      type: "warning",
    });
  }

  envType(typeForm).then((res: any) => {
    if (res.code == 200) {
      ElMessage({
        message: "操作成功",
        type: "success",
      });

      Object.assign(typeForm, {
        name: null,
        envKey: null,
        remark: null,
        sort: null,
      });
      isAddType.value = false;

      datalist.value = [];
      getenvTypeList();
    }
  });
};

// 切换折叠面板
const changeCollapse = (val: Item) => {
  val.isShow = !val.isShow;
  val.isActive = !val.isActive;
  if (val.isShow) {
    envParams.envTypeId = val.id;
    getenvList(val);
  }
};

// 加载下一页
const nextPage = (val: Item) => {
  envParams.pageNum += 1;
  envParams.envTypeId = val.id;
  getenvList(val);
};

const load = () => {
  if (infiniteScrollDisabled.value) return;
  // 在这里添加实际的加载逻辑
  console.log('加载更多内容');
  // 模拟加载更多数据
  // 如果没有更多数据可加载，设置 infiniteScrollDisabled.value = true;
};

const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

// 设置规则弹窗
const setrule = (val: EnvItem) => {
  ruleData.value = val;
  ruleTitle.value = val.name + "规则设置";
  isrule.value = true;
};

// 绘制通航环境
const setEarlyWarning = (warnings: EnvItem[]) => {
  if (earlyMakers.value.length > 0) {
    earlyMakers.value.forEach((ele) => {
      props.map.removeOverLay(ele);
    });
  }
  
  for (let i = 0; i < warnings.length; i++) {
    if (warnings[i].display) {
      try {
        const points = JSON.parse(warnings[i].regions || '[]');
        for (let j = 0; j < points.length; j++) {
          const polygon = mapUtils.createPolygon(points[j] || points, {
            color: warnings[i].borderColor,
            weight: warnings[i].borderWidth,
            opacity: 0.5,
            fillColor: warnings[i].fillColor,
            fillOpacity: 0.5,
          });
          
          // 向地图上添加面
          props.map.addOverLay(polygon);
          earlyMakers.value.push(polygon);
          
          polygon.addEventListener("mouseover", (e: MapEvent) => {
            if (e.containerPoint) {
              tranLeft.value = e.containerPoint.x - 300 + "px";
              tranTop.value = e.containerPoint.y - 100 + "px";
            }

            Object.assign(envirData, {
              title: warnings[i].name,
              type: setenvType(warnings[i].envType as number),
              remark: warnings[i].remark || '',
            });
            envirShow.value = true;
          });
          
          polygon.addEventListener("mouseout", () => {
            envirShow.value = false;
          });
        }
      } catch (error) {
        console.error('解析regions数据出错:', error);
      }
    } else if (warnings[i].regions2) {
      try {
        const points = JSON.parse(warnings[i].regions2);
        for (let j = 0; j < points.length; j++) {
          const polygon = mapUtils.createPolyline(points[j], {
            color: 'blue',
            weight: warnings[i].borderWidth,
            opacity: 0.5,
          });
          
          // 向地图上添加面
          props.map.addOverLay(polygon);
          earlyMakers.value.push(polygon);
          
          polygon.addEventListener("mouseover", (e: MapEvent) => {
            if (e.containerPoint) {
              tranLeft.value = e.containerPoint.x - 300 + "px";
              tranTop.value = e.containerPoint.y - 100 + "px";
            }

            Object.assign(envirData, {
              title: warnings[i].name,
              type: setenvType(warnings[i].envType as number),
              remark: warnings[i].remark || '',
            });
            envirShow.value = true;
          });
          
          polygon.addEventListener("mouseout", () => {
            envirShow.value = false;
          });
        }
      } catch (error) {
        console.error('解析regions2数据出错:', error);
      }
    }
  }
};

// 查询类型
const setenvType = (id: number): string => {
  let str = "";
  datalist.value.forEach((ele) => {
    if (ele.id == id) {
      str = ele.name;
    }
  });
  return str;
};

// 搜索功能
const handleSearch = () => {
  if (searchText.value) {
    // 过滤数据列表
    const filteredList = datalist.value.filter(item => 
      item.name.toLowerCase().includes(searchText.value.toLowerCase()) ||
      item.list.some(subItem => 
        subItem.name.toLowerCase().includes(searchText.value.toLowerCase())
      )
    );
    
    // 如果有匹配项，展开匹配的分类
    if (filteredList.length > 0) {
      filteredList.forEach(item => {
        if (!item.isShow) {
          item.isShow = true;
          item.isActive = true;
          envParams.envTypeId = item.id;
          getenvList(item);
        }
      });
    }
  } else {
    // 如果搜索框为空，重置所有数据
    datalist.value.forEach(item => {
      if (item.isShow) {
        item.isShow = false;
        item.isActive = false;
      }
    });
  }
};

</script>
<style scoped>
.content {
  width: 100%;
  max-width: 260px;
  height: 100%;
  z-index: 1000;
  display: flex;
  flex-direction: row;
}

.flex-column {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.flex-row {
  width: 100%;
  height: 30px;
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 0 0 10px 10px;
  margin-bottom: 10px;
  border-bottom: 1px solid #cccccc;
}

.content-txt1 {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: rgb(203, 208, 246);
  cursor: pointer;
}

.content-txt1>img {
  width: 20px;
  height: 20px;
  margin-right: 10px;
}

.iconcolor {
  color: #409EFF;
  transition: transform 0.3s ease;
}

.active {
  transform: rotate(90deg);
}

.close {
  width: 15px;
  height: 15px;
}

.line {
  width: 100%;
  height: 1px;
  margin: 10px auto;
  background: #d5d5d5;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;
  padding-right: 8px;
  color: #308ff1;
}

.custom-tree-node-label {
  display: block;
  width: 125px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  color: #308ff1;
  text-align: left;
}

.iconfont {
  font-size: 20px;
  margin-left: 5px;
}

.add-view {
  width: 350px;
  height: 400px;
  background-color: #41496f;
  padding: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: fixed;
  top: 60px;
  right: 350px;
  z-index: 10;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.edit-tool {
  width: 500px;
  background: #fff;
  position: fixed;
  bottom: 0;
  right: 0;
  z-index: 9999;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  padding: 5px 10px;
}

.edit-icon {
  color: #fff;
  width: 30px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  border-radius: 50%;
  background: #409eff;
  cursor: pointer;
}

.column-line {
  width: 1px;
  height: 20px;
  background: #d5d5d5;
}

input {
  border: none;
  outline: none;
  background: #2d2f4c;
  color: #ffffff;
}

.inpBox {
  display: flex;
  align-items: center;
  justify-content: space-around;
  margin-bottom: 20px;
}

.elinp {
  width: 200px;
}

.typeBox {
  color: #ffffff;
}

.typeBox_title {
  width: 80px;
}

.typeBox>div {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.shipContent {
  height: 700px;
  overflow: auto;
  width: 100%;
}

.envName {
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 180px;
}

.envFun {
  margin-right: 10px;
  font-size: 16px;
}

.envFun:hover {
  cursor: pointer;
  color: #409eff;
}

.envItem {
  color: #ffffff;
  margin-bottom: 10px;
  padding-left: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.envloading {
  width: 100%;
  text-align: center;
  color: #ffffff;
  padding: 10px 0;
  transition: background-color 0.3s ease;
}

.envloading:hover {
  cursor: pointer;
  background-color: rgba(64, 158, 255, 0.1);
}

.condition_item {
  display: flex;
  align-items: center;
  padding-left: 10px;
  font-size: 14px;
}

.condition_item_inp {
  height: 40px;
  width: 100%;
}

.inp {
  width: 180px;
  height: 40px;
  border: 1px solid #dcdfe6 !important;
  padding: 0 15px;
  outline: none;
  background: #2d2f4c;
  color: #ffffff;
  font-size: 16px;
  border-radius: 4px;
  margin-left: 10px;
}

.infoWindow {
  padding: 10px;
  position: fixed;
  width: 250px;
  background-color: rgba(31, 63, 130, 0.8);
  z-index: 999;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
}

.infoWindow_title {
  height: 30px;
  font-weight: bold;
  color: #ffffff;
  border-bottom: 2px solid #5fd3fc;
}

.infoWindow_text {
  height: 24px;
  line-height: 24px;
  display: flex;
  align-items: center;
  color: #5fd3fc;
  font-size: 14px;
}

.infoWindow_text>div:first-child {
  width: 80px;
  color: #ffffff;
}

:deep(.el-collapse-item__arrow) {
  display: none;
}

:deep(input[type="number"]::-webkit-inner-spin-button),
:deep(input[type="number"]::-webkit-outer-spin-button) {
  height: auto;
  -webkit-appearance: none;
}

/* 按钮样式优化 */
:deep(.el-button--small) {
  font-size: 12px;
  padding: 7px 15px;
}

:deep(.el-tooltip) {
  cursor: pointer;
}

:deep(.el-icon) {
  vertical-align: middle;
}

/* 滚动条设置 */
/* 滚动条凹槽的颜色，还可以设置边框属性  */
::-webkit-scrollbar-track-piece {
  background-color: #022044;
}

/* 滚动条的宽度  */
::-webkit-scrollbar {
  width: 10px;
}

/* 滚动条的设置  */
::-webkit-scrollbar-thumb {
  background-color: #8e97d9;
  background-clip: padding-box;
  border-radius: 5px;
}

::-webkit-scrollbar-thumb:hover {
  background-color: #5fd3fc;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .add-view {
    width: 90%;
    right: 5%;
    left: 5%;
  }
  
  .inp {
    width: 150px;
  }
  
  .shipContent {
    height: 500px;
  }
}
</style>
<style scoped src="@/assets/datePark.css"></style>